import React, { useState, useEffect } from "react";
import "./Login.css";
import { useNavigate } from "react-router-dom";
import { QqOutlined, WechatOutlined } from "@ant-design/icons";
import axios from "./axios";
import { Form, Input, Button, Toast } from "antd-mobile";
import { EyeInvisibleOutline, EyeOutline } from "antd-mobile-icons";

export default function Login() {
  const navigate = useNavigate();
  const [visible, setVisible] = useState(false);
  const [username, setUsername] = useState("");
  const [phone, setPhone] = useState("");
  const [password, setPassword] = useState("");
  const [yzm, setYzm] = useState("");
  const [code, setCode] = useState("");
  const [state, setState] = useState(false);
  const [show, setShow] = useState(false);
  let timer = "";
  let [time, setTime] = useState(60);
  const [status, setStatus] = useState(false);

  const handle = async () => {
    const res = await axios.post("/lz/code", { phone });
    if (res.data.success == true) {
      Toast.show({
        icon: "success",
        content: "验证码发送成功",
      });
      setYzm(res.data.code);
    }
    setShow(true);
    timer = setInterval(() => {
      setTime((time -= 1));
      if (time == 0) {
        setShow(false);
        setTime(60);
        clearInterval(timer);
      }
    }, 1000);
  };

  const login = async () => {
    if (username && password) {
      const res = await axios.post("/lz/login", { username, password });
      if (res.data.code == 200) {
        localStorage.setItem(
          "token",
          JSON.stringify({ username, password, status })
        );
        localStorage.setItem("data", JSON.stringify(res.data.data));
        localStorage.setItem("user", JSON.stringify(res.data.data._id));
        localStorage.setItem("username", JSON.stringify(res.data.data.username));
        navigate("/shou");
      } else {
        Toast.show({
          icon: "fail",
          content: "用户名或密码错误",
        });
      }
    } else if (phone && code) {
      const res = await axios.post("/lz/login", { phone, code });
      if (res.data.code == 200) {
        localStorage.setItem("token", JSON.stringify({ phone, code, status }));
        navigate("/");
      }
    } else {
      Toast.show({
        icon: "fail",
        content: "请输入正确的信息",
      });
    }
  };

  useEffect(() => {
    const token = localStorage.getItem("token");
    if (JSON.parse(token)?.status) {
      setPassword(JSON.parse(token).password);
      setPhone(JSON.parse(token).phone);
      setStatus(JSON.parse(token).status);
    }
  }, []);

  const check = /^1[3-9]\d{9}$/;

  return (
    <div className="login-container">
      <div className="login-card">
        <div className="login-header">
          <h1 className="login-title">校夕夕</h1>
          <p className="login-subtitle">校园二手交易平台</p>
        </div>
        
        <div className="login-tabs">
          <button
            className={`login-tab ${!state ? "active" : ""}`}
            onClick={() => setState(false)}
          >
            密码登录
          </button>
          <button
            className={`login-tab ${state ? "active" : ""}`}
            onClick={() => setState(true)}
          >
            验证码登录
          </button>
        </div>

        <div className="login-form">
          <Form style={{ display: state ? "none" : "block" }}>
            <Form.Item
              name="username"
              rules={[{ required: true, message: "请输入用户名" }]}
            >
              <Input
                placeholder="请输入用户名"
                value={username}
                onChange={(e) => setUsername(e)}
                className="login-input"
              />
            </Form.Item>
            
            <Form.Item
              name="password"
              rules={[
                { required: true, message: "请输入密码" },
                {
                  pattern: /^[a-zA-Z0-9]{6,18}$/,
                  message: "密码是6-18位，且只能包含数字和字母",
                },
              ]}
            >
              <div className="password-input-container">
                <Input
                  placeholder="请输入密码"
                  value={password}
                  onChange={(e) => setPassword(e)}
                  type={visible ? "text" : "password"}
                  className="login-input"
                />
                <div className="eye-icon">
                  {!visible ? (
                    <EyeInvisibleOutline onClick={() => setVisible(true)} />
                  ) : (
                    <EyeOutline onClick={() => setVisible(false)} />
                  )}
                </div>
              </div>
            </Form.Item>
          </Form>

          <Form style={{ display: !state ? "none" : "block" }}>
            <Form.Item
              name="phone"
              rules={[
                { required: true, message: "请输入手机号" },
                { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号" },
              ]}
            >
              <div className="phone-input-container">
                <Input
                  placeholder="请输入手机号"
                  clearable
                  value={phone}
                  onChange={(e) => setPhone(e)}
                  maxLength={11}
                  className="login-input"
                />
                <button
                  onClick={handle}
                  className={`send-code-btn ${show ? "hidden" : ""} ${
                    check.test(phone) ? "" : "disabled"
                  }`}
                  disabled={!check.test(phone)}
                >
                  发送验证码
                </button>
              </div>
            </Form.Item>
            
            <Form.Item
              name="code"
              rules={[
                { required: true, message: "请输入验证码" },
                { pattern: /^\d{6}$/, message: "请输入正确的验证码" },
                {
                  validator: (rule, value, callback) => {
                    if (value !== yzm) {
                      callback("验证码错误");
                    }
                  },
                },
              ]}
            >
              <Input
                placeholder="请输入验证码"
                value={code}
                onChange={(e) => setCode(e)}
                className="login-input"
              />
              {show && (
                <div className="countdown-text">
                  验证码已发送，{time}秒后可重新获取
                </div>
              )}
            </Form.Item>
          </Form>
        </div>

        <div className="login-options" style={{ display: !state ? "flex" : "none" }}>
          <label className="remember-me">
            <input
              type="checkbox"
              checked={status}
              onChange={(e) => setStatus(e.target.checked)}
            />
            <span>记住我</span>
          </label>
          <span className="register-link">
            没有账号？
            <span onClick={() => navigate("/zhu")}>点此注册</span>
          </span>
        </div>

        <div className="login-button">
          <Button
            color="primary"
            block
            onClick={login}
            shape="rounded"
            size="large"
          >
            登录
          </Button>
        </div>
      </div>
    </div>
  );
}